package edu.java.texbooks.scjp.threads.test05.deadlock;

public class Deadlock implements Runnable {

	public static void main(String[] args) {
		Object a = "Resource A";
		Object b = "Resource B";

		Thread thread1 = new Thread(new Deadlock(a, b));
		Thread thread2 = new Thread(new Deadlock(b, a));

		thread1.start();
		thread2.start();
	}

	private Object firstResource;
	private Object secondResource;

	public Deadlock(Object firstResource, Object secondResource) {
		super();
		this.firstResource = firstResource;
		this.secondResource = secondResource;
	}

	@Override
	public void run() {
		while (true) {
			System.out.println(Thread.currentThread().getName() + " allocates "
					+ firstResource);
			synchronized (firstResource) {
				System.out.println(Thread.currentThread().getName()
						+ " try to attempt " + secondResource);
				synchronized (secondResource) {
					System.out.println(" trying ");
					try {
						Thread.sleep(100);
					} catch (InterruptedException ie) {
						System.out.println("Thread interrupted");
					}
				}
			}
		}

	}

}
